/*
 * Copyright (c) 2014 laidian. All Rights Reserved.
 * @author yaoyuming
 * @date  2020-07-20 17:14
 */
package com.yao.common.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.yao.common.bean.LoginUser;
import com.yao.common.constant.SysConst;
import com.yao.common.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author yaoyuming
 * @date 2020/07/20 17:14
 */
@Slf4j
//@Component
//@WebFilter(filterName = "myfilter", urlPatterns = "/**")
public class AuthFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("初始化filter-----------"+filterConfig.getFilterName());
        log.info("初始化filter-----------"+filterConfig.getServletContext());
        log.info("初始化filter-----------"+filterConfig.getInitParameterNames());
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("---- 鉴权过滤 ----");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader(SysConst.TOKEN_KEY);



        if (checkToken(token)) {
            filterChain.doFilter(servletRequest, servletResponse);
        }else{
            log.error("鉴权失败.");
        }
    }


    private boolean checkToken(String token) {

        if (StrUtil.isBlank(token)) {
            return false;
        }

        String res = RedisUtils.get(SysConst.PRE_ACCESS_TOKEN + token);

        LoginUser loginUser;

        try {
            loginUser = JSON.parseObject(res, LoginUser.class);
        } catch (JSONException e) {
            log.error("解析失败.", e);
            return false;
        }

        log.info("登陆用户:{}", loginUser);

        return true;
    }


}